package com.motong.gongdan.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.CommonTree;
import com.motong.gongdan.entity.DeviceInfo;
import com.motong.gongdan.entity.LampBox;
import com.motong.gongdan.entity.LampType;
import com.motong.gongdan.service.CommonTreeService;
import com.motong.gongdan.service.DeviceInfoService;
import com.motong.gongdan.service.LampBoxService;
import com.motong.gongdan.service.LampTypeService;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.vo.system.tree.query.TreeDelQuery;
import com.motong.gongdan.vo.system.tree.query.TreeQuery;
import com.motong.gongdan.vo.system.tree.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "通用树结构请求")
@RestController
@RequestMapping("/sys/tree")
public class TreeController {


    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private LampTypeService lampTypeService;

    @Resource
    private CommonTreeService commonTreeService;

    @Resource
    private LampBoxService lampBoxService;

    @ApiOperation("获取树结构")
    @PostMapping("/list")
    @UserLoginToken
    public ResponseData<List<TreeVo>> getList(@RequestBody(required = false) TreeQuery param) {
        param = Optional.ofNullable(param).orElse(new TreeQuery());
        List<TreeVo> list = commonTreeService.getList(param);
        return ResponseData.success(list);
    }


    @ApiOperation("添加树结构信息")
    @PostMapping("/edit")
    @UserLoginToken
    public ResponseData<String> edit(@RequestBody CommonTree tree) {
        boolean isUpdate = Objects.nonNull(tree.getId());
        Integer loginUserId = Optional.ofNullable(LoginUtil.getLoginUserId()).orElse(1);
        tree.setUpdateUser(loginUserId.toString());
        tree.setUpdateTime(new Date());
        if (!isUpdate) {
            tree.setCreateUser(loginUserId.toString());
            tree.setCreateTime(new Date());
            if (Objects.isNull(tree.getParentId())) {
                tree.setParentId(0L);
            }

            if (Objects.isNull(tree.getSort())) {
                Page<CommonTree> lastData = commonTreeService.page(new Page<>(1, 1), new LambdaQueryWrapper<CommonTree>().orderByDesc(CommonTree::getSort));
                if (!CollectionUtils.isEmpty(lastData.getRecords())) {
                    tree.setSort(Optional.ofNullable(lastData.getRecords().get(0).getSort()).orElse(0) + 1);
                } else {
                    tree.setSort(0);
                }
            }
        }
        commonTreeService.saveOrUpdate(tree);
        if (!isUpdate && tree.getBelongModule() == 0) {
            List<LampBox> lampBoxes = new ArrayList<>(5);
            LampBox lampBoxR = new LampBox().setButtonName("红灯").setColor("#dc143c").setGroupId(tree.getId()).setUpdateTime(new Date()).setUpdateUser(LoginUtil.getLoginUserId());
            LampBox lampBoxY = new LampBox().setButtonName("黄灯").setColor("#ff9900").setGroupId(tree.getId()).setUpdateTime(new Date()).setUpdateUser(LoginUtil.getLoginUserId());
            LampBox lampBoxG = new LampBox().setButtonName("绿灯").setColor("#339900").setGroupId(tree.getId()).setUpdateTime(new Date()).setUpdateUser(LoginUtil.getLoginUserId());
            LampBox lampBoxB = new LampBox().setButtonName("蓝灯").setColor("#68a8fc").setGroupId(tree.getId()).setUpdateTime(new Date()).setUpdateUser(LoginUtil.getLoginUserId());
            LampBox lampBoxW = new LampBox().setButtonName("白灯").setColor("#fff").setGroupId(tree.getId()).setUpdateTime(new Date()).setUpdateUser(LoginUtil.getLoginUserId());
            lampBoxes.add(lampBoxR);
            lampBoxes.add(lampBoxY);
            lampBoxes.add(lampBoxG);
            lampBoxes.add(lampBoxB);
            lampBoxes.add(lampBoxW);
            lampBoxService.saveBatch(lampBoxes);
        }
        return ResponseData.success("请求成功!");
    }


    @ApiOperation("删除树结构")
    @PostMapping("/del")
    @UserLoginToken
    public ResponseData<String> del(@RequestBody TreeDelQuery query) {
        if (CollectionUtils.isEmpty(query.getIds())) {
            return ResponseData.fail("不要参数不能为空!");
        }

        long existDeviceCount = deviceInfoService.count(new LambdaQueryWrapper<DeviceInfo>().in(DeviceInfo::getGroupId, query.getIds()));
        if (existDeviceCount > 0) {
            return ResponseData.fail("当前分组下存在设备，请清除设备后再删除!");
        }

        long existLampTypeCount = lampTypeService.count(new LambdaQueryWrapper<LampType>().in(LampType::getGroupId, query.getIds()));
        if (existLampTypeCount > 0) {
            return ResponseData.fail("当前分组下存在联络灯类型，请清除类型后再删除!");
        }

        Set<Long> allRemoveIds = this.getAllRemoveIds(commonTreeService, query.getIds());
        commonTreeService.removeByIds(allRemoveIds);

        // 删除联络灯盒子配置
        lampBoxService.remove(new LambdaQueryWrapper<LampBox>().in(LampBox::getGroupId, allRemoveIds));
        return ResponseData.success("请求成功!");
    }


    public Set<Long> getAllRemoveIds(CommonTreeService commonTreeService, Set<Long> parentIds) {
        Set<Long> childIds = commonTreeService.list(new LambdaQueryWrapper<CommonTree>().in(CommonTree::getParentId, parentIds).select(CommonTree::getId)).stream().map(CommonTree::getId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(childIds)) {
            parentIds.addAll(childIds);
            Set<Long> allRemoveIds = this.getAllRemoveIds(commonTreeService, childIds);
            parentIds.addAll(allRemoveIds);
        }
        return parentIds;
    }


}
